<?php

namespace App\Tools\FileManager;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class QiniuManager extends BaseManager
{
    /**
     * 获取所有文件
     *
     * @param  string $path
     * @return array
     */
    public function getFileList($path)
    {
        $files = [];

        $filesContent = $this->disk->listContents($path, true);

        foreach ($filesContent as $file) {
            $files[] = $this->fileDetail($file);
        }

        return $files;
    }

    /**
     * 获取文件信息
     *
     * @param $file
     * @return array
     */
    public function fileDetail($file)
    {
        $path = $file['path'];

        return [
            'name' => $path,
            'fullPath' => $path,
            'webPath'  => $this->disk->privateImagePreviewUrl($path),
            'mimeType' => $this->fileMimeType($path),
            'size'     => $this->fileSize($path),
            'modified' => $this->fileModified($path)
        ];
    }

    /**
     * 获取图片预览 `URL`
     *
     * @param string $path
     * @return string
     */
    public function fileWebPath($path)
    {
        // 如果你使用的是七牛的私有 `bucket`, 则使用 `privateImagePreviewUrl` 方法获取图片预览 `url`
        return $this->disk->imagePreviewUrl($path);
    }

    /**
     * Handle the file upload.
     *
     * @param \Symfony\Component\HttpFoundation\File\UploadedFile $file
     * @param string                                              $dir
     * @param string                                              $name
     *
     * @return array|bool
     */
    public function store(UploadedFile $file, $dir = '', $name = '')
    {
        $hashName = empty($name)
            ? str_ireplace('.jpeg', '.jpg', $file->hashName())
            : $name;

        $mime = $file->getMimeType();

        $realPath = $this->disk->putFileAs($dir, $file, $hashName);

        return [
            'success' => true,
            'filename' => $hashName,
            'original_name' => $file->getClientOriginalName(),
            'mime' => $mime,
            'size' => human_filesize($file->getClientSize()),
            'real_path' => $realPath,
            'relative_url' => $realPath,
            'url' => $this->disk->url($realPath),
        ];
    }
}
